<?php
/**
* author:hc
* 初始化
*/
defined('HC_APP') OR exit('No direct script access allowed');

//ajax JSON.stringify(data); 返回处理
function ajaxs_from($arguments){
	$data=array();
		$data_arr = json_decode($arguments,true);
		foreach($data_arr as $key=>$val){
			$k=$val['name'];
			$v=$val['value'];
			if(isset($data[$k])){
				$data[$k].="_".$v;
			}else{
				$data[$k]=$v;
			}
		}
		return $data;
}
//短信宝
function smsbao($mobile,$content){
	$statusStr = array(
		"0" => "短信发送成功",
		"-1" => "参数不全",
		"-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
		"30" => "密码错误",
		"40" => "账号不存在",
		"41" => "余额不足",
		"42" => "帐户已过期",
		"43" => "IP地址限制",
		"50" => "内容含有敏感词"
	);
	$smsapi = "http://api.smsbao.com/";
	$user = "pzhgd"; //短信平台帐号
	$pass = md5("Pzhgd@520"); //短信平台密码
	$sendurl = $smsapi."sms?u=".$user."&p=".$pass."&m=".$mobile."&c=".urlencode($content);
	$result =file_get_contents($sendurl) ;
	if($result==0){
		return true;
	}else{
		return false;
	}
}
//数组排序.//排序比较时 要用数字；
function array_sort($array=array(),$keys,$type='asc'){
   $keysvalue = $new_array = array();
   //提取排序的列
   foreach ($array as $k=>$v){
       $keysvalue[$k] = $v[$keys];
   }
   if($type == 'asc'){
       asort($keysvalue);//升序排列
   }else{
       arsort($keysvalue);//降序排列
   }
   //reset($keysvalue);
   foreach ($keysvalue as $k=>$v){
       $new_array[$k] = $array[$k];
   }
   return $new_array;
}

//截取字符串长度
function hc_msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) {
        if(function_exists("mb_substr"))
            $slice = mb_substr($str, $start, $length, $charset);
        elseif(function_exists('iconv_substr')) {
            $slice = iconv_substr($str,$start,$length,$charset);
        }else{
            $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
            $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
            $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
            $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
            preg_match_all($re[$charset], $str, $match);
            $slice = join("",array_slice($match[0], $start, $length));
        }
        return $suffix ? $slice.'...' : $slice;
}
/**
* UTF-8编码 GBK编码相互转换/（支持数组）
*
* @param array $str?? 字符串，支持数组传递
* @param string $in_charset 原字符串编码
* @param string $out_charset 输出的字符串编码
* @return array
*/
function array_iconv($str,$in_charset='gbk',$out_charset='utf-8'){
	if(is_array($str)){
		foreach($str as $k=>$v){
			$str[$k]=array_iconv($v);
		}
		return $str;
	}elseif(is_string($str)){
		return mb_convert_encoding($str, $out_charset, $in_charset);
	}else{
		return $str;
	}
}
//数据库调用
function M($table=''){
		$config=include(CORE_PATH.'/config/database.php');
		$db=\hc\pdodb::getinstance($config);
		$db->table($table);
		return $db;
}
//解析session_set_save_handler session 序列号session.serialize_handler。
function sess_un($data_value) {
	 $vars = preg_split(
		 '/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\|/',
		 $data_value, -1, PREG_SPLIT_NO_EMPTY |
		 PREG_SPLIT_DELIM_CAPTURE
	 );
	 for ($i = 0; isset($vars[$i]); $i++) {
		 $result[$vars[$i++]] = unserialize($vars[$i]);
	 }
	 return $result;
}
//获取ip
function getip($type = 0) {
    $type       =  $type ? 1 : 0;
    static $ip  =   NULL;
    if ($ip !== NULL) return $ip[$type];
    if(isset($_SERVER['HTTP_X_REAL_IP'])){//nginx 代理模式下，获取客户端真实IP
        $ip=$_SERVER['HTTP_X_REAL_IP'];
    }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {//客户端的ip
        $ip     =   $_SERVER['HTTP_CLIENT_IP'];
    }elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {//浏览当前页面的用户计算机的网关
        $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos    =   array_search('unknown',$arr);
        if(false !== $pos) unset($arr[$pos]);
        $ip     =   trim($arr[0]);
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip     =   $_SERVER['REMOTE_ADDR'];//浏览当前页面的用户计算机的ip地址
    }else{
        $ip=$_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u",ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}
function getipLocation($ip=''){
 empty($ip) && $ip = getip();
 if($ip=="127.0.0.1") return "本机地址";
 $api = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=$ip";
 $json = @file_get_contents($api);//调用新浪IP地址库
 $arr = json_decode($json,true);//解析json
 $country = $arr['country']; //取得国家
 $province = $arr['province'];//获取省份
 $city = $arr['city']; //取得城市
 if((string)$country == "中国"){
  if((string)($province) != (string)$city){
   $_location = $province.$city;
  }else{
   $_location = $country.$city;
  }
 }else{
  $_location = $country;
 }
 return $_location;
}
/**
* 返回访问设备
*
* @return
*/
function get_agent(){
	$agent=strtolower($_SERVER['HTTP_USER_AGENT']);
	if(strpos($agent,'windows nt')){
		$platform = 'windows';
	}elseif(strpos($agent,'macintosh')){
		$platform="mac";
	}elseif(strpos($agent,'ipod')){
		$platform="ipod";
	}elseif(strpos($agent,'ipad')){
		$platform="ipad";
	}elseif(strpos($agent,'iphone')){
		$platform="iphone";
	}elseif(strpos($agent,'android')){
		$platform="android";
	}elseif(strpos($agent,'linux')){
		$platform="linux";
	}elseif(strpos($agent, 'unix')){
		$platform="unix";
	}else{
		$platform="other";
	}
	return $platform;
}
function is_mobile(){
	$_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : '';
	$mobile_browser = '0';
	if(preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i', strtolower($_SERVER['HTTP_USER_AGENT'])))
		$mobile_browser++;
	if((isset($_SERVER['HTTP_ACCEPT'])) and (strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') !== false))
		$mobile_browser++;
	if(isset($_SERVER['HTTP_X_WAP_PROFILE']))
	 	$mobile_browser++;
	if(isset($_SERVER['HTTP_PROFILE']))
	 	$mobile_browser++;
	 $mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,4));
	 $mobile_agents = array(
			'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
			'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
			'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
			'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
			'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
			'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
			'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
			'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
			'wapr','webc','winw','winw','xda','xda-'
	 );
	if(in_array($mobile_ua, $mobile_agents))
		 $mobile_browser++;
	if(strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false)
		 $mobile_browser++;
	 // Pre-final check to reset everything if the user is on Windows
	if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') !== false)
		 $mobile_browser=0;
		 // But WP7 is also Windows, with a slightly different characteristic
	if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') !== false)
		$mobile_browser++;
	if($mobile_browser>0)
		return true;
 	else
		return false;
}
/**
 * UTF-8编码 GBK编码相互转换/（支持数组）
 *
 * @param array $str   字符串，支持数组传递
 * @param string $in_charset 原字符串编码
 * @param string $out_charset 输出的字符串编码
 * @return array
 */
function hc_iconv($str,$in_charset='gbk',$out_charset='utf-8'){
	if(is_array($str)){
		foreach($str as $k=>$v){
			$str[$k]=cms_iconv($v);
		}
		return $str;
	}elseif(is_string($str)){
		return mb_convert_encoding($str, $out_charset, $in_charset);
	}else{
		return $str;
	}
}
/**
* 验证长度
* 在$start 和 $end 之间 return true; 反之return false;
* @如果只有$start 小于$satrt return true;反之return false;
*/
function hc_length($str,$start='',$end=''){
	$length=strlen($str);
	if($start && $end){
		if($length<$start || $length>$end){
			return false;
		}else{
			return true;
		}
	}elseif($start && $end==''){
		if($length<$start){
			return false;
		}else{
			return true;
		}
	}
}
/**
* 产生随机字符串
* 数字及字母
* @param    int        $length  输出长度
* @param    string     $chars   可选的 ，默认为 0123456789
* @return   string     字符串
*/
function hc_mtrand($length){
	$hash = '';
	//第一位不能为0；
	$charsone="123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";
	$maxone = strlen($charsone) - 1;
	$hash.= $charsone[mt_rand(0, $maxone)];

	$chars = '0123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ';
	$max = strlen($chars) - 1;
	for($i = 0; $i < $length-1; $i++) {
		$hash .= $chars[mt_rand(0, $max)];
	}
	return $hash;
}
//mysql safe 处理
function mysql_safe($str,$rule='escape'){
	if($rule=='escape'){//转义
		//PHP 指令 magic_quotes_gpc 为 on，系统会对所有的 GET、POST 和 COOKIE 数据自动运行 addslashes() 。不
		if (!get_magic_quotes_gpc()){
    		return addslashes($str);
		} else {
    		return $str;
		}
	}elseif($rule=='noescape'){//反转
		return stripslashes($str);
	}elseif($rule=='entity'){//html 添加实体
		return htmlspecialchars($str);
	}elseif($rule=='noentity'){//解封html 实体
		return htmlspecialchars_decode($str);
	}elseif($rule=='delhtmllable'){//去掉字符串中的html 实体
		return strip_tags($str);
	}elseif($rule=='enter_br'){//将字符中的回车替换成<br>;
		return nl2br($str);
	}
}
/**
* 正则验证
* @return
*/
function check_regex($value,$rule) {
    $validate = array(
    		'istell'    =>  '/^([0-9]{3,4}-)?[0-9]{7,8}$/',//tell 验证
    		'ismobile'  =>  '/^1[3|4|5|7|8][0-9]\d{8}$/',//手机
        'email'     =>  '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',//邮箱
        'url'       =>  '/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(:\d+)?(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/',
        'number'    =>  '/^\d+$/',
        'integer'   =>  '/^[-\+]?\d+$/',
        'double'    =>  '/^[-\+]?\d+(\.\d+)?$/',
        'english'   =>  '/^[A-Za-z]+$/',
        'englishh'   =>  '/^[A-Za-z|]+$/',//只能是字母和|
        'englishx'  =>  '/^[A-Za-z_]+$/',//字母加下划线
        'isnozh'    =>	'/^[a-zA-Z0-9]+$/',
        'dir'      	=>	'/^[a-zA-Z0-9_\/]+$/',//目录结果
        'card'		=>  '/^(\d{18,18}|\d{15,15}|\d{17,17}x)$/',
        'price'     =>  "/^\d+\.?\d{0,2}$/",
        'iszhen'    =>  '/[\x7f-\xff]/',//存在中文 no 不存在中文
        'iszhen2'   =>  '/^[\x{4e00}-\x{9fa5}]+$/u',//全是中文  no 不全是中文
        'comstrunderline'    =>  '/^[0-9a-zA-Z_\x{4e00}-\x{9fa5}]+$/iu',//中文 英文 数字 下划线
				'title'    =>  '/^[0-9a-zA-Z\?\。\x{4e00}-\x{9fa5}]+$/iu',//中文 英文 数字 下划线 ? .
        'comstr'    =>  '/^[0-9a-zA-Z\x{4e00}-\x{9fa5}]+$/iu',//中文 英文 数字
        'filename'	=> 	'/^[A-Za-z0-9_.]+$/',//文件名验证
        );
        // 检查是否有内置的正则表达式
        if(isset($validate[strtolower($rule)]))
            $rule = $validate[strtolower($rule)];
        return preg_match($rule,$value)===1;
}
/**
* 内部码：及代表含义
* @param undefined $code
*
* @return
*/
function ajax_return($status,$msg,$data=false){
	$ajax_return['msg']=$msg;
	$ajax_return['status']=$status;
	$ajax_return['data']=$data;
	echo json_encode($ajax_return);exit;
}
//密码加密规则
function hc_pass($opwd){
		$string="aokerui";
		$string=md5(sha1($string));
		$pwd=sha1(md5($opwd));
		$pwd=$pwd.$string;
		$pwd=sha1(md5($pwd));
		$pwd="AoKeRuiPGC".$pwd;
		return $pwd;
	//$p1=hash("sha256",$password."mcms");
	//return md5($p1."mcms");
}
//添加转义 和返转义
function hc_escape($string,$type='add'){
    if($type == 'add'){
        if (get_magic_quotes_gpc()){
					return $string;
				}else{
					if(function_exists('addslashes')){
                return addslashes($string);
					}else{
						return mysql_real_escape_string($string);
          }
        }
    }elseif($type == 'strip'){
        return stripslashes($string);
    }else{
			die('error in PHP_slashes (mixed,add | strip)');
    }
}

?>
